package com.sdk.springbootjwt;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (redisTemplate.hasKey("jwt:blacklist:" + token)) {
            throw new JWTVerificationException("Invalid token"); // 主动拒绝已失效的Token‌:ml-citation{ref="5" data="citationList"}
        }
        try {
            String username = JwtUtil.validateToken(token);
            request.setAttribute("username", username);
            return true;
        } catch (TokenExpiredException e) {
            response.setHeader("X-Token-Expired", "true");
            response.setStatus(401);
            return false;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }
}

